import 'dart:io';

class BudgetManager {
  final List<Map<String, dynamic>> incomes = [];
  final List<Map<String, dynamic>> expenses = [];

  double get totalIncome => incomes.fold(0, (sum, item) => sum + item['amount']);
  double get totalExpenses => expenses.fold(0, (sum, item) => sum + item['amount']);
  double get netProfit => totalIncome - totalExpenses;
  double get tax => netProfit > 0 ? netProfit * 0.15 : 0;

  void addIncome(String description, double amount) {
    incomes.add({'description': description, 'amount': amount});
    print("\n✅ Income added: $description (\$${amount.toStringAsFixed(2)})");
  }

  void addExpense(String description, double amount) {
    expenses.add({'description': description, 'amount': amount});
    print("\n❌ Expense added: $description (\$${amount.toStringAsFixed(2)})");
  }

  void deleteIncome(int index) {
    if (index >= 0 && index < incomes.length) {
      final removed = incomes.removeAt(index);
      print("\n🗑️ Removed income: ${removed['description']} (\$${removed['amount']})");
    } else {
      print("⚠️ Invalid index!");
    }
  }

  void deleteExpense(int index) {
    if (index >= 0 && index < expenses.length) {
      final removed = expenses.removeAt(index);
      print("\n🗑️ Removed expense: ${removed['description']} (\$${removed['amount']})");
    } else {
      print("⚠️ Invalid index!");
    }
  }

  void editIncome(int index, String newDescription, double newAmount) {
    if (index >= 0 && index < incomes.length) {
      incomes[index] = {'description': newDescription, 'amount': newAmount};
      print("\n✏️ Income updated successfully!");
    } else {
      print("⚠️ Invalid index!");
    }
  }

  void editExpense(int index, String newDescription, double newAmount) {
    if (index >= 0 && index < expenses.length) {
      expenses[index] = {'description': newDescription, 'amount': newAmount};
      print("\n✏️ Expense updated successfully!");
    } else {
      print("⚠️ Invalid index!");
    }
  }

  void displaySummary() {
    print("\n=====================================");
    print(" 📊 Budget Summary ");
    print("=====================================");
    print("💰 Total Income:     \$${totalIncome.toStringAsFixed(2)}");
    print("💸 Total Expenses:   \$${totalExpenses.toStringAsFixed(2)}");
    print("📈 Net ${netProfit >= 0 ? 'Profit' : 'Loss'}:  \$${netProfit.abs().toStringAsFixed(2)}");

    if (tax > 0) {
      print("📝 Tax to be paid (15%): \$${tax.toStringAsFixed(2)}");
    }
    print("=====================================\n");
  }

  void displayList(String type) {
    List<Map<String, dynamic>> list = type == 'income' ? incomes : expenses;
    print("\n--- ${type == 'income' ? 'Income' : 'Expense'} List ---");

    if (list.isEmpty) {
      print("❌ No ${type == 'income' ? 'income' : 'expenses'} recorded.");
    } else {
      for (int i = 0; i < list.length; i++) {
        print("[$i] ${list[i]['description']} - \$${list[i]['amount']}");
      }
    }
  }
}

String getValidInput(String prompt) {
  String input;
  do {
    stdout.write(prompt);
    input = stdin.readLineSync()?.trim() ?? '';
    if (input.isEmpty) {
      print("⚠️ Input cannot be empty. Please enter a valid value.");
    }
  } while (input.isEmpty);
  return input;
}

double getValidAmount(String prompt) {
  double? amount;
  do {
    stdout.write(prompt);
    amount = double.tryParse(stdin.readLineSync() ?? '');
    if (amount == null || amount <= 0) {
      print("⚠️ Amount must be a positive number!");
      amount = null;
    }
  } while (amount == null);
  return amount;
}

void clearScreen() {
  print("\x1B[2J\x1B[0;0H"); // تنظيف الشاشة بطريقة أكثر توافقية على جميع الأجهزة
}

void budgetMain() {
  final manager = BudgetManager();

  while (true) {
    clearScreen();
    print("""
=====================================
 📊 Welcome to Budget Manager  
=====================================
1️⃣ Add Income
2️⃣ Add Expense
3️⃣ View Summary
4️⃣ View Income List
5️⃣ View Expense List
6️⃣ Edit Income
7️⃣ Edit Expense
8️⃣ Delete Income
9️⃣ Delete Expense
🔟 Exit
=====================================
Enter your choice: 
""");

    final choice = stdin.readLineSync()?.trim() ?? '';

    switch (choice) {
      case '1':
        final desc = getValidInput("📝 Enter income description: ");
        final amount = getValidAmount("💰 Enter income amount: ");
        manager.addIncome(desc, amount);
        break;

      case '2':
        final desc = getValidInput("📝 Enter expense description: ");
        final amount = getValidAmount("💸 Enter expense amount: ");
        manager.addExpense(desc, amount);
        break;

      case '3':
        manager.displaySummary();
        break;

      case '4':
        manager.displayList('income');
        break;

      case '5':
        manager.displayList('expense');
        break;

      case '6':
        manager.displayList('income');
        final index = int.tryParse(getValidInput("Enter the index of the income to edit: ")) ?? -1;
        final newDesc = getValidInput("📝 Enter new description: ");
        final newAmount = getValidAmount("💰 Enter new amount: ");
        manager.editIncome(index, newDesc, newAmount);
        break;

      case '7':
        manager.displayList('expense');
        final index = int.tryParse(getValidInput("Enter the index of the expense to edit: ")) ?? -1;
        final newDesc = getValidInput("📝 Enter new description: ");
        final newAmount = getValidAmount("💸 Enter new amount: ");
        manager.editExpense(index, newDesc, newAmount);
        break;

      case '8':
        manager.displayList('income');
        final index = int.tryParse(getValidInput("Enter the index of the income to delete: ")) ?? -1;
        manager.deleteIncome(index);
        break;

      case '9':
        manager.displayList('expense');
        final index = int.tryParse(getValidInput("Enter the index of the expense to delete: ")) ?? -1;
        manager.deleteExpense(index);
        break;

      case '10':
        print("\n✅ Exiting Budget Manager. Goodbye!");
        exit(0);

      default:
        print("⚠️ Invalid choice! Please enter a number between 1-10.");
    }

    print("\n🔄 Press Enter to continue...");
    stdin.readLineSync();
  }
}

void main() {
  budgetMain();
}
